package com.yww.algorithm.sort;

import java.util.Arrays;

/**
 * @author yww
 * @description 堆排序
 * @since 2024/2/23 15:23
 */
public class HeapSort {
    public static void sort(int[] arr) {
        heapify(arr, arr.length); // 建立大顶堆

        int i = arr.length - 1; // 开始排序
        while (i > 0) {
            swap(arr, 0, i);  // 交换首位两元素
            down(arr, 0, i--); // 重新维护堆
        }
    }

    /**
     * 建堆
     */
    private static void heapify(int[] arr, int size) {
        for (int i = size / 2 - 1; i >= 0; i--) {
            down(arr, i, size);
        }
    }

    /**
     * parent 下沉，非递归版本，效率更高
     */
    private static void down(int[] arr, int parent, int size) {
        while (parent < size) {
            int left = parent * 2 + 1;
            int right = left + 1;
            int max = parent;
            if (left < size && arr[left] > arr[max]) {
                max = left;
            }
            if (right < size && arr[right] > arr[max]) {
                max = right;
            }
            if (max == parent) {
                break;
            }

            swap(arr, parent, max);
            parent = max;
        }
    }

    private static void swap(int[] a, int i, int j) {
        int t = a[i];
        a[i] = a[j];
        a[j] = t;
    }

    public static void main(String[] args) {
        int[] a = {6, 5, 4, 3, 2, 1};
        System.out.println(Arrays.toString(a));
        sort(a);
        System.out.println(Arrays.toString(a));
    }
}
